package com.example.custom.web.service.impl;


import com.example.custom.web.service.IDataService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.springframework.beans.factory.annotation.Value;


import java.util.*;


/**
 * @descriptions:
 * @author: otitan-jianghongkai
 * @date: 2023/12/29 15:40
 * @version: 1.0
 */
@Service
public class DataService implements IDataService {
    @Value("${api.base_url}")
    private String baseUrl;

    /**
     * 根据当前登录用户的信息，获取单景正射切片主题列表和服务地址
     *
     * @param password 加密后的密码
     * @param user     用户名
     * @return
     */
    @Override
    public ResponseEntity<String> callTargetApi(String password, String user) {
        // 创建HttpHeaders
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json"); // 添加头部信息

        // 创建HttpEntity对象，将头部信息与请求体一起发送
        HttpEntity<String> entity = new HttpEntity<>("{\"password\":\"" + password + "\",\"user\":\"" + user + "\"}", headers);

        // 使用RestTemplate发送POST请求到目标URL
        ResponseEntity<String> loginResponse = null;
        try {
            loginResponse = new RestTemplate().exchange(
                    baseUrl + "/v3/login", HttpMethod.POST, entity, String.class);
            if (loginResponse.getStatusCode() == HttpStatus.OK) {
                JSONObject responseJson = new JSONObject(loginResponse.getBody());
                // 检查响应体中是否包含code字段
                if (responseJson.has("code")) {
                    int errorCode = responseJson.getInt("code");
                    if (errorCode != 200) {
                        // 抛出业务异常或其他处理逻辑
                        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("调用登录接口返回错误，错误信息：" + responseJson.getString("error"));
                    }
                }
            }
        } catch (HttpStatusCodeException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("接口调用失败，状态码：" + e.getStatusCode());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("接口调用失败，状态码：" + e.getMessage());
        }
        System.out.println(loginResponse);
        // 获取实际的数据部分（JSON字符串）
        String jsonString = loginResponse.getBody();
// 提取JSON字符串中的"session"字段的值
        String session = null;
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            session = jsonObject.getString("session");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(session); // 输出"session"字段的值
        // 从登录响应中获取授权会话标识符（Auth-Session）
        // 创建切片主题列表请求的HttpHeaders，并添加Auth-Session请求头
        HttpHeaders themeHeaders = new HttpHeaders();
        themeHeaders.add("Auth-Session", session); // 添加Auth-Session请求头
        themeHeaders.add("Content-Type", "application/json"); // 添加头部信息

        // 创建HttpEntity对象，将头部信息与请求体一起发送
        HttpEntity<String> themeEntity = new HttpEntity<>("", themeHeaders);
        ResponseEntity<String> themeResponse;
        // 使用RestTemplate发送GET请求到切片主题列表接口
        try {
            themeResponse = new RestTemplate().exchange(
                    baseUrl + "/v3/themes?type=single&sort=create_time&order=desc&offset=0&limit=10",
                    HttpMethod.GET,
                    themeEntity,
                    String.class);
            if (themeResponse.getStatusCode() == HttpStatus.OK) {
                JSONObject responseJson = new JSONObject(themeResponse.getBody());
                // 检查响应体中是否包含code字段
                if (responseJson.has("code")) {
                    int errorCode = responseJson.getInt("code");
                    if (errorCode != 200) {
                        // 抛出业务异常或其他处理逻辑
                        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("调用切片主题列表接口返回错误，错误信息：" + responseJson.getString("error"));
                    }
                }
            }
        } catch (HttpStatusCodeException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("接口调用失败，状态码：" + e.getStatusCode());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("接口调用失败，状态码：" + e.getMessage());
        }
        //拿到themeResponse
        System.out.println(themeResponse);
        //  调用请求新加字段接口
        // 解析themeResponse的JSON内容
        JSONObject themeResponseJson;
        try {
            themeResponseJson = new JSONObject(themeResponse.getBody().toString());
        } catch (Exception e) {
            // 处理JSON解析异常，返回的内容不是有效的JSON
            //return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("JSON转换异常" + e.getMessage());
        }
        // 从themes列表中获取所有的主题
        JSONArray themesArray;
        try {
            themesArray = themeResponseJson.getJSONArray("themes");
        } catch (JSONException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("JSON转换异常" + e.getMessage());
        }
        List<ResponseEntity<String>> responses = new ArrayList<>();
        //定义description，从themesArray中的description获取id，用于调用新加字段接口
        String description;
        //定义id，从themesArray中获取id，用于通过数据id获取token接口
        String id;
        //定义srs ,从themesArray中获取srs，用于匹配img_info
        String srs;
        //定义拼接服务地址名称（上面）
        String assress_above = null;
        //定义拼接服务地址名称（下面）
        String assress_below;
        JSONArray resultArray = new JSONArray();
        for (int i = 0; i < themesArray.length(); i++) {
            JSONObject currentTheme;
            try {
                currentTheme = themesArray.getJSONObject(i);
                description = currentTheme.get("description").toString();
                id = currentTheme.get("id").toString();
                srs = currentTheme.get("srs").toString();
            } catch (JSONException e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("从themes列表中获取数据，JSON转换异常：" + e.getMessage());
            }
            // 从description中提取dataId
            String dataId = description.split("@@")[0]; // 假设"@@"是分隔符，前面是dataId
            // 使用dataId构造新接口的URL
            String newFieldUrl = baseUrl + "/v3/catalog/datas/" + dataId + "/metas?pre-load=false";
            // 创建HttpHeaders（如果需要特定的头部信息，否则可以省略）
            HttpHeaders newFieldHeaders = new HttpHeaders();
            newFieldHeaders.add("Content-Type", "application/json"); // 添加头部信息

            // 创建HttpEntity对象（如果需要发送请求体，否则可以省略）
            HttpEntity<String> newFieldEntity = new HttpEntity<>("", newFieldHeaders);
            // 使用RestTemplate发送GET请求到新接口
            //  ResponseEntity<String> newFieldResponse = new RestTemplate().exchange(newFieldUrl, HttpMethod.GET, null, String.class);
            ResponseEntity<String> newFieldResponse = null;
            try {
                newFieldResponse = new RestTemplate().exchange(newFieldUrl, HttpMethod.GET, newFieldEntity, String.class);
                if (newFieldResponse.getStatusCode() == HttpStatus.OK) {
                    JSONObject responseJson = new JSONObject(newFieldResponse.getBody());
                    if (responseJson.has("code")) {
                        int errorCode = responseJson.getInt("code");
                        if (errorCode != 200) {
                            // 抛出业务异常或其他处理逻辑
                            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("调用新加字段接口接口返回错误，错误信息：" + responseJson.getString("error"));
                        }
                    }
                }
            } catch (HttpStatusCodeException e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("接口调用失败，状态码：" + e.getStatusCode());
            } catch (Exception e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("接口调用失败，状态码：" + e.getMessage());
            }
            System.out.println(newFieldResponse);
            System.out.println("************************************************");
            String newFieldResponseBody = newFieldResponse.getBody();
            System.out.println(newFieldResponseBody);

            // 解析响应结果中的JSON数据
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseMap = null;
            try {
                responseMap = objectMapper.readValue(newFieldResponseBody, Map.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            // 获取"metadata"列表
            List<Map<String, Object>> metadataList = (List<Map<String, Object>>) responseMap.get("metadata");
            // 创建一个Map用于存储"name"和"value"对应的关系
            Map<String, Object> nameValueMap = new HashMap<>();
            // 遍历"metadata"列表
            for (Map<String, Object> metadata : metadataList) {
                List<Map<String, Object>> valueList = (List<Map<String, Object>>) metadata.get("value");
                for (Map<String, Object> value : valueList) {
                    String name = (String) value.get("name");
                    Object valueObj = value.get("value");
                    nameValueMap.put(name, valueObj);
                }
            }
            System.out.println(nameValueMap);
            //定义拼接服务地址变量
            String img_info = "";
            if ("EPSG:3857".equals(srs)) {
                img_info = "img_esri_w";
            } else if ("EPSG:4490".equals(srs)) {
                img_info = "img_esri_c";
            }
            // 通过数据id获取token接口
            // 构建请求URL，将id作为参数插入到URL中
            String url = baseUrl + "/v3/gisauth/tokens/resources/" + id + "/tokens";
            // 创建HttpHeaders（如果需要特定的头部信息，否则可以省略）
            HttpHeaders newTokensHeaders = new HttpHeaders();
            newTokensHeaders.add("Content-Type", "application/json"); // 添加头部信息
            // 创建HttpEntity对象（如果需要发送请求体，否则可以省略）
            HttpEntity<String> newTokenEntity = new HttpEntity<>("", newTokensHeaders);
            // 使用RestTemplate发送GET请求到新接口
            ResponseEntity<String> newTokenResponse = null;
            try {
                newTokenResponse = new RestTemplate().exchange(url, HttpMethod.GET, newTokenEntity, String.class);
                if (newTokenResponse.getStatusCode() == HttpStatus.OK) {
                    String responseBody = newTokenResponse.getBody();
                    //解析JSON响应体
                    String token = null;
                    if (newTokenResponse.getBody() != null) {
                        JSONArray jsonArray = new JSONArray(responseBody);
                        if (jsonArray.length() == 0) {
                            resultArray = new JSONArray();
                            continue;
                        } else {
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            token = jsonObject.getString("token");
                            System.out.println("token: " + token);
                            //开始拼接服务地址
                            //（上面）
                            assress_above = baseUrl + "/v3/service/wmts/" + img_info + "/" + token + "?service=wmts&request=GetCapabilities";
                        }
                    }
                }
            } catch (HttpStatusCodeException e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("接口调用失败，状态码：" + e.getStatusCode());
            } catch (Exception e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("接口调用失败，状态码：" + e.getMessage());
            }
            //添加新的内容(服务地址)
            currentTheme.put("assress_above", assress_above);
            //申请单号
            if (nameValueMap.get("application_number") != null) {
                currentTheme.put("application_number", nameValueMap.get("application_number"));
            } else {
                currentTheme.put("application_number", "");
            }
            //拍摄日期
            if (nameValueMap.get("shooting_date") != null) {
                currentTheme.put("shooting_date", nameValueMap.get("shooting_date"));
            } else {
                currentTheme.put("shooting_date", "");
            }
            //小班编号
            if (nameValueMap.get("sub_compartment_number") != null) {
                currentTheme.put("sub_compartment_number", nameValueMap.get("sub_compartment_number"));
            } else {
                currentTheme.put("sub_compartment_number", "");
            }
            //栽植号
            if (nameValueMap.get("planting_number") != null) {
                currentTheme.put("planting_number", nameValueMap.get("planting_number"));
            } else {
                currentTheme.put("planting_number", "");
            }
            //林地调查编号
            if (nameValueMap.get("forest_surver_number") != null) {
                currentTheme.put("forest_surver_number", nameValueMap.get("forest_surver_number"));
            } else {
                currentTheme.put("forest_surver_number", "");
            }
            System.out.println(currentTheme);
            resultArray.put(currentTheme);
        }
        // 创建新的ResponseEntity对象，并设置修改后的主题数组
        HttpHeaders returnHeaders = new HttpHeaders();
        returnHeaders.setContentType(MediaType.APPLICATION_JSON); // 设置响应的内容类型为JSON
        // 将修改后的数组转换为JSON字符串
        String modifiedResponseBody = resultArray.toString();
        // 创建新的ResponseEntity对象，并设置修改后的响应体
        return new ResponseEntity<>(modifiedResponseBody, headers, HttpStatus.OK);
    }


}
